<template>
  <static-content-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-id="parentId"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
  >
    <div
      v-if="field.options.tableTopLabel"
      class="field-table-top-label"
      :style="{
        backgroundColor: field.options.tableTopBgcolor,
        textAlign: field.options.tableTopLabelAlign,
        padding: field.options.tableTopLabelPadding,
        color: field.options.textColor,
      }"
    >
      {{ field.options.tableTopLabel }}
    </div>
    <template v-if="layoutType === 'PC'">
      <el-table
        :ref="fieldId"
        class="PC-table"
        v-bind="bindAttr"
        :data="formData[fieldId]"
        :border="field.options.border"
        :size="field.options.tableSize"
        :highlight-current-row="field.options.highLightCurrentRow"
      >
        <!-- :span-method="objectSpanMethod" -->
        <el-table-column
          v-if="!previewStatus && field.options.rowEnabled"
          label="操作"
          align="center"
          width="80"
        >
          <template slot-scope="table">
            <div class="field-action">
              <i
                class="el-icon-copy-document"
                title="复制"
                @click.stop="cloneRow(table)"
              />
              <i
                class="el-icon-delete"
                title="删除"
                @click.stop="removeRow(table)"
              />
            </div>
          </template>
        </el-table-column>
        <template v-for="col in ColConfig">
          <el-table-column
            :key="col.id"
            :prop="col.id"
            :label="col.options.tableLabel"
            :width="col.options.colWidth"
            :align="col.options.tableAlign"
            :show-overflow-tooltip="col.options.showOverflowTooltip"
          >
            <template slot-scope="scope">
              <component
                :is="getUnitName(col.type)"
                v-if="!!col.type"
                :field="col"
                :form-row="scope"
                :form-data="formData"
                :field-options="ColOptions[col.id]"
                :designer="designer"
                :design-state="designer.designStatus"
              />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div v-if="!previewStatus && field.options.rowEnabled" class="appendLine">
        <el-button
          type="text"
          icon="el-icon-circle-plus-outline"
          @click="addRow"
        >
          添加新一行
        </el-button>
      </div>
    </template>
    <template v-else>
      <div
        v-for="(row, $index) in formData[fieldId]"
        :key="$index"
        class="H5-table"
      >
        <el-form label-width="50px" label-position="top">
          <template v-for="col in ColConfig">
            <el-form-item :key="col.id" :label="col.options.tableLabel">
              <component
                :is="getUnitName(col.type)"
                v-if="!!col.type"
                :field="col"
                :form-row="{ row, $index }"
                :form-data="formData"
                :field-options="ColOptions[col.id]"
                :designer="designer"
                :design-state="designer.designStatus"
              />
            </el-form-item>
          </template>
        </el-form>
        <div v-if="!previewStatus && field.options.rowEnabled" class="append">
          <div class="appendLine">
            <el-button
              type="text"
              icon="el-icon-copy-document"
              @click="cloneRow({ row, $index })"
            >
              复制
            </el-button>
          </div>
          <div v-if="formData[fieldId].length !== 1" class="appendLine">
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="removeRow({ row, $index })"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </template>
  </static-content-wrapper>
</template>

<script>
/* eslint-disable vue/require-default-prop */
/* eslint-disable eol-last */
import StaticContentWrapper from "../static-content-wrapper";
import emitter from "Yan/utils/emitter";
import i18n from "Yan/utils/i18n";
import fieldMixin from "../fieldMixin";
import TableColUnits from "./table_col/index";
import request from "@/utils/request";

function overwriteObj(obj1, obj2) {
  Object.keys(obj2).forEach((prop) => {
    if (!obj1[prop]) obj1[prop] = obj2[prop];
  });
}
export default {
  name: "table_unit",
  componentName: "FieldWidget",
  components: {
    StaticContentWrapper,
    ...TableColUnits,
  },
  mixins: [emitter, fieldMixin, i18n],
  props: {
    designer: Object,
    fieldId: String,
    parentId: String,
    parentList: Array,
    indexOfParentList: Number,
    formData: Object,
    designState: {
      type: Boolean,
      default: false,
    },
  },
  // inject: ['refList', 'formConfig', 'globalOptionData', 'globalModel'],
  data() {
    return {
      oldFieldValue: null,
      tempModel: [],
      ColConfig: [],
      ColOptions: {},
      ColSpanLib: [],
      ColSummaryLib: {},
      rules: [],
    };
  },
  computed: {
    designStatus() {
      return this.designer.designStatus;
    },
    bindAttr() {
      const attr = {};
      if (this.designer.previewStatus && this.ColSpanLib.indexOf(true) !== -1) {
        attr["span-method"] = this.objectSpanMethod;
      }
      return attr;
    },
  },
  // watch: {
  //   [`formData.${this.fieldId}`]: {
  //     handler(n) {
  //       console.log(n);
  //     },
  //   },
  // },
  created() {
    if (this.designStatus) {
      this.designer.handleEvent("tableColField_Change", this.reSetColList);
      this.designer.handleEvent("tableColChange", this.reSetDefaultValue);
    }
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
         需要在父组件created中初始化！！ */
    // this.initOptionItems();
    // this.initFieldModel();
    // this.registerToRefList();
    this.initEventHandler();
    this.buildFieldRules();

    this.handleOnCreated();
    this.reSetColList();
  },

  mounted() {
    this.designer.handleEvent(`tableDoLayout_${this.fieldId}`, () => {
      // console.log("table doLayout");
      this.$refs[this.fieldId].doLayout();
    });
    this.handleOnMounted();
    // console.log(this.formData[this.fieldId]);
    this.$watch(
      `formData.${this.fieldId}`,
      (n) => {
        // console.log(n);
        this.onColSummaryHandle(n);
      },
      {
        deep: true,
      }
    );
    // this.$watch(`formData.${this.fieldId}`, this.handleColSummary);
  },

  methods: {
    getUnitName(unit) {
      return unit + "_unit";
    },
    hasUnitType(unit) {
      return !!this.fieldLib[unit].type;
    },
    /* 开启任意级节点可选后，点击radio隐藏下拉框 */
    hideDropDownOnClick() {
      setTimeout(() => {
        document
          .querySelectorAll(".el-cascader-panel .el-radio")
          .forEach((el) => {
            el.onclick = () => {
              this.$refs.fieldEditor.dropDownVisible = false;
            };
          });
      }, 100);
    },
    // 初始化表格默认值
    reSetDefaultValue() {
      // console.log("reSetDefaultValue");
      if (this.designStatus) {
        const renderList = this.field.options.tableCols.filter(
          (i) => this.fieldLib[i].type !== null
        );
        const addLib = {};
        let defaultRowValue = [{}];
        if (this.field.options.defaultRowValue) {
          defaultRowValue = JSON.parse(this.field.options.defaultRowValue);
        }

        renderList.forEach((i) => {
          const rowField = this.fieldLib[i];
          addLib[i] = (function () {
            if (rowField.type === "table_checkbox") return [];
            else if (rowField.type === "table_switch") return false;
            else return null;
          })();
        });
        defaultRowValue.forEach((i) => overwriteObj(i, addLib));
        this.field.options.defaultRowValue = JSON.stringify(
          defaultRowValue,
          null,
          "  "
        );
        // console.log(this.field.options.defaultRowValue);
        this.reSetColList();
      }
    },
    // 初始化表格列选项
    async reSetColList() {
      // console.log("reSetColList");
      // if(this.designer.previewStatus)
      this.$set(this, "ColConfig", []);
      await this.$nextTick();
      const renderList = this.field.options.tableCols.filter((i) => {
        const hasType = this.fieldLib[i].type !== null;
        const designShow = this.designer.designStatus;
        const previewShow = Object.prototype.hasOwnProperty.call(
          this.fieldLib[i].options,
          "perviewShow"
        )
          ? this.fieldLib[i].options.perviewShow && this.designer.previewStatus
          : true;
        const renderShow = Object.prototype.hasOwnProperty.call(
          this.fieldLib[i].options,
          "renderShow"
        )
          ? this.fieldLib[i].options.renderShow && !this.designer.designStatus
          : true;
        return (hasType && (designShow || renderShow)) || previewShow;
      });
      const list = renderList.map((i) => this.fieldLib[i]);
      list.forEach((i) => {
        if (i.options.optionItemsAsync) this.loadColOptionsAsync(i);
      });
      this.$set(this, "ColConfig", list);
      this.reSetTableData();
    },
    // 初始化表格列选项
    async loadColOptionsAsync(field) {
      const customFn = new Function("request", field.options.optionItemsAsync);
      const OptionItems = await customFn.call(this, request);
      // console.log("handleOptionItemsAsync", field.id, OptionItems);
      if (OptionItems) this.$set(this.ColOptions, field.id, OptionItems);
    },
    // 初始化表格行 默认值
    reSetTableData() {
      // console.log("reSetTableData");
      const temp_data = {};
      this.ColConfig.forEach((i) => {
        temp_data[i.id] = i.options.defaultValue;
        this.ColSpanLib.push(
          i.options.colSpanMethod !== void 0 ? i.options.colSpanMethod : false
        );
        if (i.options.colSummary) {
          this.ColSummaryLib[i.id] = i.options.colSummary;
        }
      });
      // 有合计需求的列会进行合计并输出到指定字段
      if (
        !this.designer.previewStatus &&
        Object.keys(this.ColSummaryLib).length > 0
      ) {
        this.$watch(`formData.${this.fieldId}`, this.onColSummaryHandle, {
          deep: true,
          immediate: true,
        });
      }
      this.tempModel = temp_data;
    },
    // 列数值合计
    onColSummaryHandle(n) {
      // console.log(
      //   `table_unit @${this.fieldId} ColSummary in`,
      //   n.length,
      //   Object.keys(this.ColSummaryLib)
      // );
      const keylist = Object.keys(this.ColSummaryLib);
      const outLib = {};
      keylist.forEach((key) => {
        if (!outLib[key]) outLib[key] = 0;
        const dataArr = n.map((i) => i[key]);
        // console.log(key, "=>", dataArr);
        let colSumVal = 0;
        // console.log(key, "#", this.fieldLib[key].options.colSummaryHandle);
        if (this.fieldLib[key].options.colSummaryHandle) {
          const colSumFn = new Function(
            "value",
            this.fieldLib[key].options.colSummaryHandle
          );
          const Val = colSumFn.call(this, dataArr);
          // console.log(key, "@", Val);
          if (colSumVal !== void 0) colSumVal = Val;
        } else {
          colSumVal = dataArr.reduce((total, num) => total + Number(num), 0);
        }
        outLib[key] = colSumVal;
      });
      // console.log("ColSummaryLib", outLib);
      keylist.forEach((key) => {
        this.formData[this.ColSummaryLib[key]] = outLib[key];
      });
      // console.log(`table_unit @${this.fieldId} ColSummary=>`, outLib);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(row, column, rowIndex, columnIndex);
      if (this.ColSpanLib) {
        return { rowspan: 1, colspan: 1 };
      }
      return { rowspan: 1, colspan: 1 };
    },
    addRow() {
      this.formData[this.fieldId].push({ ...this.tempModel });
    },
    cloneRow(data) {
      this.formData[this.fieldId].splice(data.$index + 1, 0, { ...data.row });
    },
    removeRow(data) {
      this.formData[this.fieldId].splice(data.$index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../../styles/global.scss"; //* form-item-wrapper已引入，还需要重复引入吗？ *//
.field-table-top-label {
  margin: 0 !important;
  height: 3em;
  line-height: 3em;
  font-size: 16px;
  // display: flex;
  // align-items: center;
  border-color: #ebeef5;
  border-style: solid;
  border-width: 1px 1px 0 1px;
}
.appendLine {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  border: 1px solid #ebeef5;
  border-top: 0;
}
.PC-table + .appendLine:hover {
  background-color: #ecf5ff;
}
.field-action {
  height: 22px;
  line-height: 22px;

  i {
    font-size: 14px;
    color: $--color-primary;
    margin: 0 5px;
    cursor: pointer;
  }
}
::v-deep {
  .H5-table {
    padding: 6px;
    border-top: 3px solid #ebeef5;
    .append {
      display: flex;
      justify-content: space-between;
      .appendLine {
        flex: 1;
        border: 0;
        .el-button {
          margin-right: 0;
        }
      }
    }
  }
  .el-form-item {
    margin-bottom: 6px;
    // &:last-child {
    //   margin-bottom: 0;
    // }
    .el-form-item__label {
      // line-height: 1.6em;
      padding-bottom: 0;
    }
  }
  .el-table .cell {
    padding-left: 4px;
    padding-right: 4px;
  }
  // .el-input__inner {
  //   padding: 0 8px;
  // }
  // .el-date-editor .el-input__inner {
  //   padding: 0 8px;
  // }
}
</style>
